package com.wx.activitys.drp.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.sd4324530.fastweixin.api.response.GetUserInfoResponse;
import com.wx.activitys.base.utils.EmojiFilter;
import com.wx.activitys.drp.JsonResult;
import com.wx.activitys.drp.EnumUtils.EnumTream;
import com.wx.activitys.drp.model.BUserInfo;
import com.wx.activitys.drp.service.DigitalSignature;
import com.wx.activitys.drp.service.UserInfoService;


@Controller
@RequestMapping("/user")
public class RegisterController {
	@Autowired
	UserInfoService userInfoService;
	
	@RequestMapping(method = { RequestMethod.POST }, value = "/add.html")
	@ResponseBody
	public JsonResult add(BUserInfo bUserInfo, HttpServletRequest request ) {
		GetUserInfoResponse userInfo = ((GetUserInfoResponse)request.getSession().getAttribute("userInfo"));
		String spread = (String) request.getSession().getAttribute("spread");
		String onOpenId = (String) request.getSession().getAttribute("onOpenId");
		if(StringUtils.isNotBlank(userInfo.getOpenid())){
			BUserInfo buserinfo = userInfoService.findByOpenid(userInfo.getOpenid());
			if(buserinfo!=null){
				return JsonResult.success("你的微信号已注册嘉华金融", userInfo);
			}
			bUserInfo.setOpenid(userInfo.getOpenid());
			bUserInfo.setHeadImgUrl(userInfo.getHeadimgurl());
			bUserInfo.setWxCity(userInfo.getCity());
			bUserInfo.setWxCountry(userInfo.getCountry());
			String nk = EmojiFilter.filterEmoji(userInfo.getNickname());
			bUserInfo.setWxNickname(nk);
			bUserInfo.setWxSex(userInfo.getSex());
			bUserInfo.setWxProvince(userInfo.getProvince());
			bUserInfo.setCreateTime(new Date());
			bUserInfo.setRoleKey("1");
			bUserInfo.setIncome(0.0);
			bUserInfo.setTreamRole(EnumTream.经销商.getValue());
			if(StringUtils.isNotBlank(onOpenId)){
				BUserInfo buserinfo1 = userInfoService.findByOpenid(onOpenId);
				if(buserinfo1.getRoleKey().equals("1")){
					bUserInfo.setTreamRole(EnumTream.经销商.getValue());
				}else{
					if(buserinfo1.getTreamRole().equals(EnumTream.经销商.getValue())){
						bUserInfo.setTreamRole(EnumTream.分销商1级.getValue());
					}else if(buserinfo1.getTreamRole().equals(EnumTream.分销商1级.getValue())){
						bUserInfo.setTreamRole(EnumTream.分销商2级.getValue());
					}else if(buserinfo1.getTreamRole().equals(EnumTream.分销商2级.getValue())){
						bUserInfo.setTreamRole(EnumTream.经销商.getValue());
					}	
				}
				bUserInfo.setpId(onOpenId);
			}
			if(StringUtils.isNotBlank(spread)){
				bUserInfo.setSpread(spread);
			}
			bUserInfo.setState(1);
			Integer flag= userInfoService.insertAndupdate(bUserInfo,onOpenId);
			if(flag>0){
				return JsonResult.success("注册成功", userInfo.getSubscribe());
			}else{
				return JsonResult.success("注册失败", bUserInfo);
		}
		}else{
			return JsonResult.success("openid为空", bUserInfo);
		}
	}
	
	/**
	 * 检查电话号码是否被注册
	 * @param bUserInfo
	 * @param request
	 * @return
	 */
	@RequestMapping(method = { RequestMethod.POST}, value = "/checkPhone.html")
	@ResponseBody
	public JsonResult check(@RequestParam String phone, HttpServletRequest request ) {
		Map<String,Object> map = new HashMap<>();
		map.put("phone", phone);
		map.put("state", 1);
		List<BUserInfo> list=userInfoService.selectByMap(map);
		if(list.size()>0){
			return JsonResult.success("手机号码已注册", list);
		}else{
			return JsonResult.success("手机号码未注册", list);
		}		
	}

	/*
	 * 检查验证码是否正确
	 */
	@RequestMapping(method = { RequestMethod.GET }, value = "/checkCode.html")
	@ResponseBody
	public JsonResult validate(HttpServletRequest request){
		String code = request.getParameter("code");  
		HttpSession session = request.getSession();  
		String sessionCode = (String) session.getAttribute("code");
		if (!sessionCode.equalsIgnoreCase(code)) {  //忽略验证码大小写  
			return JsonResult.success("1","验证码不对");  
		}	
		return JsonResult.success("2","");
	}
	
	
	/**
	 * 卡卡贷接口跳转
	 * @param request
	 * @param response
	 */
	@RequestMapping(method = { RequestMethod.GET }, value = "/kkd.html")
	public void tokkd(HttpServletRequest request, HttpServletResponse response){
		 String uuid = DigitalSignature.getUUID();
	        long timestamp = System.currentTimeMillis();
	        String data = uuid + "jiahua" + timestamp;
	        //数字签名加密
	        String signature=null;
			try {
				signature = DigitalSignature.signBase64(data, DigitalSignature.PRIVATE_KEY);
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				response.sendRedirect("http://third.kkcredit.cn/#/wcIndex/init?uuid="+uuid+"&source=jiahua&timestamp="+timestamp+"&signature="+URLEncoder.encode(signature,"utf-8"));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
	}
	
}
